﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using ZBZH_Manage_Order.Models;
using ZBZH_Manage_Order.PublicMethod;

namespace ZBZH_Manage_Order.Controllers.TakerMangement
{
    public class SendController : Controller
    {
        //派送管理控制器
        // GET: /Send/

        //连接服务
        ServiceReference1.Service1Client wsdcser = new ServiceReference1.Service1Client();

       
        public ActionResult Index()
        {
            Model.View_OperUser user = (Model.View_OperUser)Session[SessionStorage.OperUser];

            if (user == null)
            {
                return RedirectToAction("LoginPage", "Login");  //czx:修改为登录者的Session异常时，直接跳转到登录页面
            }

            int OperID = user.OperID;
            ViewData["OperID"] = OperID;
        
            return View();
        }

        /// <summary>
        /// 根据调度员ID获取需要调度的派送单
        /// </summary>
        /// <param name="OperID"></param>
        /// <param name="jqgridparam"></param>
        /// <returns></returns>
        public ActionResult GetSendForm(string FormID, string FormControl, string FormTimeS, string FormTimeE, JqGridParam jqgridparam)
        {
            try
            {
                Model.View_OperUser user = (Model.View_OperUser)Session[SessionStorage.OperUser];

                if (user == null)
                {
                    return RedirectToAction("LoginPage", "Login");  //czx:修改为登录者的Session异常时，直接跳转到登录页面
                }

                int OperID = user.OperID;
                Page<Model.Order_Send_T> page = new Page<Model.Order_Send_T>();//分页类定义
                List<Model.View_Order_Form> list = new List<Model.View_Order_Form>();

                FormTimeS = FormTimeS.Replace("-", "");
                FormTimeE = FormTimeE.Replace("-", "");
                string result = wsdcser.GetOrder_SendByOperId(OperID, FormControl, FormTimeS, FormTimeE, FormID, jqgridparam.page, jqgridparam.rows, GetYZM._YZM, 1);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                if (bs == "1")//返回结果正常
                {
                    IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                    if (jieguo.Count > 0)
                    {
                        list = ParseClass<Model.View_Order_Form>.JsonList(jieguo);//解析返回的结果\
                    }
                    var data = new
                    {
                        total = searcho["total"].ToString(),
                        rows = list
                    };
                    return Json(data);
                }
                else
                {
                    var data = new
                    {
                        total = "0",
                        rows = list
                    };
                    return Json(data);
                }
            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
        }
        /// <summary>
        /// 根据操作员id获取下面的派送员
        /// </summary>
        /// <param name="OperID"></param>
        /// <param name="jqgridparam"></param>
        /// <returns></returns>
        public ActionResult GetTakerByOper(string OperID, JqGridParam jqgridparam)
        {
            try
            {
                List<Model.Order_Taker_T> list_ot = new List<Model.Order_Taker_T>();
                string result = wsdcser.GetOrder_Taker(OperID, 2, 1, 10000, GetYZM._YZM, 1);
                JObject searcho = JObject.Parse(result);
                string bs = searcho["BS"].ToString();
                if (bs == "1")
                {
                    IList<JToken> jieguo = searcho["rows"].Children().ToList();
                    if (jieguo.Count > 0)
                    {
                        list_ot = ParseClass<Model.Order_Taker_T>.JsonList(jieguo);
                    }
                    var data = new
                    {
                        total = searcho["total"].ToString(),
                        rows = list_ot
                    };
                    return Json(list_ot, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    var data = new
                    {
                        total = "0",
                        rows = list_ot
                    };
                    return Json(list_ot);
                }
            }
            catch (Exception ex)
            {
                return Json("操作异常："+ex+"请联系管理员解决");
            }
        }

        /// <summary>
        /// 指派
        /// </summary>
        /// <param name="Tag"></param>
        /// <param name="os"></param>
        /// <returns></returns>
        public ActionResult Assign(int Tag,Model.Order_Send_T os) 
        {
            try
            {
                Model.View_OperUser user = (Model.View_OperUser)Session[SessionStorage.OperUser];
                os.SendState= 1;
                string json = os.ToJson();
                string result = wsdcser.SetFormToTaker(json, Tag, "", 1);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();
                if (bs == "1")
                {
                    return Content(bs);
                }
                else
                {
                    return Content(searcho["Msg"].ToString());
                }
            }
            catch (Exception)
            {
                return null;
            }
        }

        public ActionResult getFormID(int formID)
        {
            try
            {
                List<Model.View_Order_Form> list = new List<Model.View_Order_Form>();
                string result = wsdcser.GetFormByID(formID, GetYZM._YZM, 1);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                if (bs == "1")//返回结果正常
                {
                    IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                    if (jieguo.Count > 0)
                    {
                        list = ParseClass<Model.View_Order_Form>.JsonList(jieguo);//解析返回的结果\
                        foreach (Model.View_Order_Form item in list)
                        {
                            item.FormTime = DateTimeHelper.ToDate2(item.FormTime);
                            if (item.SenTime.Length == 14)
                            {
                                item.SenTime = DateTimeHelper.ToDate2(item.SenTime);
                            }
                        }
                    }
                    var data = new
                    {
                        total = searcho["total"].ToString(),
                        rows = list
                    };
                    return Json(data, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    var data = new
                    {
                        total = "0",
                        rows = list
                    };
                    return Json(data, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
        }


        public ActionResult getDishesgrid(string Dishes, JqGridParam jqgridparam)
        {
            try
            {
                Page<DishesForm> page = new Page<DishesForm>();//分页类定义
                List<DishesForm> list = new List<DishesForm>();
                string[] str_Dis = Dishes.Split('|');
                string[] str_DisID = str_Dis[0].Split(',');
                string[] str_DisName = str_Dis[1].Split(',');
                string[] str_DisNun = str_Dis[2].Split(',');
                string[] str_DisMon = str_Dis[3].Split(',');
                string[] str_DisInt = str_Dis[4].Split(',');
                for (int i = 0; i < str_DisID.Length; i++)
                {
                    DishesForm DishesForm = new DishesForm();
                    DishesForm.FormDishesID = str_DisID[i];  //菜品ID集合
                    DishesForm.FormDisheName = str_DisName[i]; // 菜品名称集合
                    DishesForm.FormDishesNun = int.Parse(str_DisNun[i]); //菜品数量集合
                    DishesForm.FormDishesMon = DataHelper.MoneyToYuang(str_DisMon[i]); //菜品原单价集合
                    if (str_DisInt.Length == 1)
                    {
                        DishesForm.FornDishesInt = "0";
                    }
                    else
                    {
                        DishesForm.FornDishesInt = str_DisInt[i];
                    }
                    if (DishesForm.FormDishesMon != "0")
                    { DishesForm.FornDishesCount = DataHelper.MoneyToYuang((int.Parse(str_DisMon[i]) * DishesForm.FormDishesNun).ToString()); }
                    else
                    { DishesForm.FornDishesCount = (int.Parse(str_DisInt[i]) * DishesForm.FormDishesNun).ToString(); }
                    list.Add(DishesForm);
                }
                if (list.Count > 0)
                {
                    jqgridparam.records = list.Count;//查询的数据总数
                    var data = new
                    {
                        total = list.Count.ToString(),
                        rows = page.FindListPage(list, ref jqgridparam)
                    };
                    return Json(data);
                }
                else
                {
                    var data = new
                    {
                        total = "0",
                        rows = list
                    };
                    return Json(data);
                }
            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
        }

        #region 获取订单下拉状态
        public ActionResult getFormBY(int FormID)
        {
            try
            {

                List<Model.Order_FormControl_T> List = new List<Model.Order_FormControl_T>();
                List<Zcd> lsk = new List<Zcd>();//按钮list
                string result = wsdcser.GetFromConID(FormID, "012002", 1, GetYZM._YZM, 1);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                if (bs == "1")//返回结果正常
                {
                    IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                    List = ParseClass<Model.Order_FormControl_T>.JsonList(jieguo);//解析返回的结果

                    return Json(List, JsonRequestBehavior.AllowGet);
                    
                }
                else
                {
                    return null;
                }

            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
        }
        #endregion

        /// <summary>
        /// 获取订单状态信息
        /// </summary>
        /// <returns></returns>
        public ActionResult getOrderFormType()
        {
            try
            {
                List<Model.Order_FormControl_T> list_Order_FormType = new List<Model.Order_FormControl_T>();//定义商品分类设置
                string result = wsdcser.GetFromConID(609, "012002", 0, GetYZM._YZM, 1);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                if (bs == "1")
                {
                    IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                    list_Order_FormType = ParseClass<Model.Order_FormControl_T>.JsonList(jieguo);//解析返回的结果\
                    return Json(list_Order_FormType, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json("加载异常！");
                }
            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
        }

        /// <summary>
        /// czx:获取是否有新的订单到达。20160725
        /// </summary>
        /// <param name="MerID">当前商户ID</param>  
        /// <returns></returns>
        public ActionResult getOrder(int OrderId)
        {
            try
            {
                string result = wsdcser.GetNewOrderIdByPS(OrderId, "", 1); //调用WebService，传入当前商户的最大ID的订单号。 返回格式：{"BS":"1","Msg":"查询成功","total":6,"rows":null}

                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                if (bs == "1")//查询成功
                {
                    int total = Convert.ToInt32(searcho["total"].ToString());

                    if (total > 0)
                    {
                        return Json(total.ToString());  //有新的订单到达
                    }
                    else
                    {
                        return Json("-1");

                    }
                }


                return Json("-1");
            }
            catch (Exception ex)
            {
                return Json("-1");
            }


        }


        /// <summary>
        ///设置按钮的id和名称
        /// </summary>
        public class Zcd
        {
            public int id { get; set; }
            public string name { get; set; }
        }


        public class DishesForm
        {
            public string FormDishesID { get; set; }//商品ID
            public string FormDisheName { get; set; }//商品名称
            public int FormDishesNun { get; set; }//商品数量
            public string FormDishesMon { get; set; }//商品价格
            public string FornDishesInt { get; set; }//商品积分
            public string FornDishesCount { get; set; }//商品价格积分合计
        }

    }
}
